import React, { useEffect, useMemo, useState } from 'react';
import { Space, Button, Upload, InputNumber, Input, List, Typography, message } from 'antd';
import Drager from './Drager';

const { Text } = Typography;

// 参考 merchant-end-111 的默认图层配置
const defaultLayers = [
  { id: 'layer-18', name: '语言', type: 'text', text: 'EN', left: 110, top: 15, width: 50, height: 15, visible: true, zIndex: 18, color: '#fff', fontSize: 15, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-17', name: '标题4字体', type: 'text', text: 'Postcard Print', left: 166, top: 305, width: 90, height: 10, visible: true, zIndex: 17, color: '#fff', fontSize: 12, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-16', name: '标题3字体', type: 'text', text: 'Upload Print', left: 38, top: 305, width: 100, height: 15, visible: true, zIndex: 16, color: '#fff', fontSize: 12, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-15', name: '标题2字体', type: 'text', text: 'Take Photo', left: 25, top: 260, width: 90, height: 10, visible: true, zIndex: 15, color: '#fff', fontSize: 12, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-14', name: '标题1字体', type: 'text', text: 'Instagram Print', left: 25, top: 170, width: 100, height: 50, visible: true, zIndex: 14, color: '#fff', fontSize: 12, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-13', name: '标题', type: 'text', text: 'PRINT YOUR BEAUTIFUL PHOTO', left: 45, top: 75, width: 200, height: 50, visible: true, zIndex: 13, color: '#fff', fontSize: 12, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-12', name: 'icon3', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/home_Postcard_jpg.png', left: 145, top: 305, width: 24, height: 24, visible: true, zIndex: 12, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-11', name: 'icon3', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/home_QR_jpg.png', left: 20, top: 305, width: 24, height: 24, visible: true, zIndex: 11, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-10', name: 'icon3', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/Phoprint_LOGO.png', left: 87, top: 50, width: 95, height: 23, visible: true, zIndex: 10, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-9', name: 'icon3', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/icon_Camera.png', left: 50, top: 215, width: 44, height: 44, visible: true, zIndex: 9, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-8', name: 'icon2', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/home_ins_jpg.png', left: 50, top: 125, width: 44, height: 44, visible: true, zIndex: 8, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-7', name: 'icon1', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/home_icon_language.png', left: 100, top: 20, width: 15, height: 15, visible: true, zIndex: 7, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-6', name: '背景5', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/AI_img.png', left: 139, top: 110, width: 119, height: 175, visible: true, zIndex: 6, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-5', name: '背景4', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/home_bg02_img.png', left: 139, top: 295, width: 119, height: 50, visible: true, zIndex: 5, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-4', name: '背景3', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/home_bg02_img.png', left: 12, top: 295, width: 119, height: 50, visible: true, zIndex: 4, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-3', name: '背景2', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/home_bg01_img.png', left: 12, top: 200, width: 119, height: 85, visible: true, zIndex: 3, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-2', name: '背景1', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/home_bg01_img.png', left: 12, top: 110, width: 119, height: 85, visible: true, zIndex: 2, boundary: true, rotatable: true, resizable: true },
  { id: 'layer-1', name: '背景图层', type: 'image', imgUrl: 'https://foreign-phoprint.oss-us-east-1.aliyuncs.com/phoprint/custom/bg_img.png', left: 0, top: 0, width: 270, height: 480, visible: true, zIndex: 1, boundary: true, rotatable: false, resizable: false },
];

export default function HomeTemplate({
  layerList = [],
  selectedLayer = null,
  basicInsertInfo = {},
  onLayerUpdated,
  onLayerSelected,
  onCanvasSaved,
  onCanvasCleared,
}) {
  // 状态管理
  const [layers, setLayers] = useState([]);
  const [selected, setSelected] = useState(null);
  const [textColor, setTextColor] = useState('#ffffff');
  const [fontSize, setFontSize] = useState(12);

  // 初始化或从 props 恢复图层
  useEffect(() => {
    if (Array.isArray(layerList) && layerList.length > 0) {
      setLayers(layerList.map((l, idx, arr) => ({ ...l, zIndex: arr.length - idx })));
    } else {
      setLayers(defaultLayers);
    }
  }, [JSON.stringify(layerList)]);

  useEffect(() => {
    setSelected(selectedLayer || null);
  }, [selectedLayer]);

  // 根据机器功能过滤可见图层
  const machineFunctions = useMemo(() => basicInsertInfo?.machineFunction || [], [basicInsertInfo]);
  const visibleLayers = useMemo(() => {
    return (layers || []).filter((layer) => {
      if (['layer-2', 'layer-3', 'layer-8', 'layer-9', 'layer-14', 'layer-15'].includes(layer.id)) {
        if (layer.id === 'layer-3' || layer.id === 'layer-9' || layer.id === 'layer-15') {
          return layer.visible && machineFunctions.includes('1');
        }
        if (layer.id === 'layer-2' || layer.id === 'layer-8' || layer.id === 'layer-14') {
          return layer.visible && machineFunctions.includes('2');
        }
        return false;
      }
      return layer.visible;
    });
  }, [JSON.stringify(layers), JSON.stringify(machineFunctions)]);

  // 事件派发
  const emitLayers = (updated) => {
    onLayerUpdated && onLayerUpdated(updated);
  };

  const selectLayer = (layer) => {
    setSelected(layer);
    setTextColor(layer?.color || '#ffffff');
    setFontSize(layer?.fontSize || 12);
    onLayerSelected && onLayerSelected(layer);
  };

  const updateSelectedField = (key, value) => {
    if (!selected) return;
    const updated = layers.map((l) => (l.id === selected.id ? { ...l, [key]: value } : l));
    setLayers(updated);
    const newSel = updated.find((l) => l.id === selected.id);
    setSelected(newSel);
    emitLayers(updated);
  };

  const saveCanvas = () => {
    const canvasData = { layers, canvasSize: { width: 270, height: 480 } };
    onCanvasSaved && onCanvasSaved(canvasData);
    message.success('首页画布已保存');
  };

  const clearCanvas = () => {
    setLayers([]);
    setSelected(null);
    onCanvasCleared && onCanvasCleared();
    emitLayers([]);
    message.success('首页画布已清空');
  };

  // 新增图层（上传图片）
  const handleUploadNewLayer = async ({ file, onSuccess, onError }) => {
    try {
      const url = URL.createObjectURL(file);
      const newLayer = {
        id: `layer-upload-${Date.now()}`,
        name: file.name || '上传图层',
        type: 'image',
        imgUrl: url,
        left: 10,
        top: 10,
        width: 60,
        height: 60,
        visible: true,
        zIndex: layers.length + 1,
        boundary: true,
        rotatable: true,
        resizable: true,
      };
      const updated = [...layers, newLayer];
      setLayers(updated);
      emitLayers(updated);
      onSuccess && onSuccess('ok');
      message.success('已新增图片图层');
    } catch (e) {
      onError && onError(e);
    }
  };

  // 替换选中图层图片
  const handleReplaceImage = async ({ file, onSuccess, onError }) => {
    try {
      if (!selected || selected.type !== 'image') {
        return onError && onError(new Error('请选择一个图片图层'));
      }
      const url = URL.createObjectURL(file);
      updateSelectedField('imgUrl', url);
      onSuccess && onSuccess('ok');
      message.success('图片已替换');
    } catch (e) {
      onError && onError(e);
    }
  };

  const deleteSelectedLayer = () => {
    if (!selected) return;
    if (!String(selected.id).startsWith('layer-upload-')) {
      return message.warning('仅支持删除上传生成的图层');
    }
    const updated = layers.filter((l) => l.id !== selected.id);
    setLayers(updated);
    setSelected(null);
    emitLayers(updated);
    message.success('图层已删除');
  };

  // 画布区域渲染（使用 Drager 提供拖拽能力）
  const renderLayer = (layer) => {
    const innerStyle = {
      width: '100%',
      height: '100%',
      border: selected?.id === layer.id ? '1px dashed #1890ff' : 'none',
      color: layer.color,
      fontSize: layer.fontSize,
    };
    return (
      <Drager
        width={layer.width}
        height={layer.height}
        left={layer.left}
        top={layer.top}
        boundary
        boundaryWidth={270}
        boundaryHeight={480}
        style={{ zIndex: layer.zIndex }}
        onDragStart={() => selectLayer(layer)}
        onChange={(pos) => updateLayerPosition(layer.id, pos)}
        onClick={() => selectLayer(layer)}
      >
        {layer.type === 'text' && (
          <div style={innerStyle}>{layer.text || '文本内容'}</div>
        )}
        {layer.type === 'image' && (
          layer.imgUrl ? (
            <img src={layer.imgUrl} alt={layer.name} style={{ ...innerStyle, objectFit: 'cover' }} />
          ) : (
            <div style={{ ...innerStyle, background: '#eee', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>占位图层</div>
          )
        )}
        {layer.type !== 'text' && layer.type !== 'image' && (
          <div style={innerStyle}>{layer.name}</div>
        )}
      </Drager>
    );
  };

  const updateLayerPosition = (id, dragData) => {
    setLayers((prev) => {
      const updated = prev.map((l) => (
        l.id === id ? { ...l, left: dragData.left, top: dragData.top, width: dragData.width, height: dragData.height } : l
      ));
      emitLayers(updated);
      return updated;
    });
  };

  return (
    <div style={{ display: 'flex', gap: 12 }}>
      {/* 左侧画布与工具栏 */}
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <Text strong>首页模版</Text>
          <Space>
            <Button onClick={clearCanvas}>清空</Button>
            <Button type="primary" onClick={saveCanvas}>保存</Button>
          </Space>
        </div>
        {/* 工具栏 */}
        <Space style={{ marginBottom: 8 }}>
          <Upload accept=".png,.jpg,.jpeg" showUploadList={false} customRequest={handleUploadNewLayer}>
            <Button type="primary">新增图层</Button>
          </Upload>
          <Upload accept=".png,.jpg,.jpeg" showUploadList={false} customRequest={handleReplaceImage} disabled={!selected || selected.type !== 'image'}>
            <Button disabled={!selected || selected.type !== 'image'}>替换图片</Button>
          </Upload>
          {/* 文本颜色（简化为hex输入） */}
          <Input
            placeholder="#ffffff"
            value={textColor}
            onChange={(e) => {
              setTextColor(e.target.value);
              updateSelectedField('color', e.target.value);
            }}
            disabled={!selected || selected.type !== 'text'}
            style={{ width: 120 }}
          />
          {/* 字体大小 */}
          <InputNumber
            min={8}
            max={72}
            step={1}
            value={fontSize}
            onChange={(val) => {
              setFontSize(val || 12);
              updateSelectedField('fontSize', val || 12);
            }}
            disabled={!selected || selected.type !== 'text'}
          />
          {/* 删除上传的图层 */}
          <Button danger disabled={!selected || !String(selected.id).startsWith('layer-upload-')} onClick={deleteSelectedLayer}>删除</Button>
        </Space>

        {/* 坐标编辑 */}
        {selected && (
          <Space style={{ marginBottom: 8 }}>
            <span>X:</span>
            <InputNumber min={0} max={270} value={selected.left} onChange={(v) => updateSelectedField('left', v || 0)} />
            <span>Y:</span>
            <InputNumber min={0} max={480} value={selected.top} onChange={(v) => updateSelectedField('top', v || 0)} />
            <span>W:</span>
            <InputNumber min={1} max={270} value={selected.width} onChange={(v) => updateSelectedField('width', v || 1)} />
            <span>H:</span>
            <InputNumber min={1} max={480} value={selected.height} onChange={(v) => updateSelectedField('height', v || 1)} />
          </Space>
        )}

        {/* 画布 */}
        <div style={{ width: 270, height: 480, background: '#f5f5f5', position: 'relative', border: '1px solid #ddd' }}>
          {visibleLayers.map((layer) => (
            <React.Fragment key={layer.id}>{renderLayer(layer)}</React.Fragment>
          ))}
        </div>
      </div>

      {/* 右侧图层列表 */}
      <div style={{ width: 250 }}>
        <div style={{ fontWeight: 600, marginBottom: 8 }}>图层列表</div>
        <List
          bordered
          dataSource={layers}
          renderItem={(item) => (
            <List.Item onClick={() => selectLayer(item)} style={{ cursor: 'pointer', background: selected?.id === item.id ? '#e6f4ff' : undefined }}>
              <Space>
                <Text>{item.name}</Text>
                <Text type="secondary">{item.type}</Text>
              </Space>
            </List.Item>
          )}
        />
      </div>
    </div>
  );
}